package fun.stgoder.easydarwin.jobs.ctl.rest;

import fun.stgoder.easydarwin.jobs.bl.BL;
import fun.stgoder.easydarwin.jobs.bl.entity.Job;
import fun.stgoder.easydarwin.jobs.comm.Code;
import fun.stgoder.easydarwin.jobs.comm.Constants;
import fun.stgoder.easydarwin.jobs.comm.model.Page;
import fun.stgoder.easydarwin.jobs.comm.model.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Api("jobs api")
@RestController
@RequestMapping("/rest/job")
public class JobRest {

    private DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //private DateFormat df = new SimpleDateFormat("yyyyMMdd");

    private Logger logger = LoggerFactory.getLogger(JobRest.class);

    @ApiOperation("add a job")
    @PostMapping({"", "/"})
    public Resp addJob(
            @RequestParam("streamId") @ApiParam(name = "streamId", value = "custom stream id", required = true) String streamId,
            @RequestParam("endTime") @ApiParam(name = "endTime", value = "job end time, format like 'yyyy-MM-dd HH:mm:ss'", required = false) String endTime)
            throws Exception {
        long lstartTime = System.currentTimeMillis();
        long lendTime;
        if (StringUtils.isNotBlank(endTime)) {
            Date dendTime = sdf.parse(endTime);
            lendTime = dendTime.getTime();
        } else {
            lendTime = lstartTime + 1000 * 60 * 30;
        }

        String jobKey = BL.JOB.addJob(streamId, lstartTime, lendTime); // job id

        logger.info("add job streamId: " + streamId);

        return new Resp(Code.REQUEST_OK, "succ", jobKey);
    }

    @ApiOperation("stop a job")
    @PostMapping("/stop/{id}")
    public Resp stopJob(@PathVariable("id") @ApiParam(name = "id", value = "job id", required = true) String id)
            throws Exception {
        logger.info("stop job id: " + id);
        BL.JOB.stopJobAndMergeFile(id);
        return new Resp(Code.REQUEST_OK, "succ", id);
    }

    @ApiOperation("get a job")
    @GetMapping("/{id}")
    public Resp getJob(@PathVariable("id") @ApiParam(name = "id", value = "job id", required = true) String id)
            throws Exception {

        Job job = BL.JOB.getJob(id);
        if (job == null)
            throw new Exception("job not found");

        return new Resp(Code.REQUEST_OK, "succ", job);
    }

    @ApiOperation("get jobs of page data")
    @GetMapping({"", "/"})
    public Resp getJobs(
            @RequestParam(value = "page", required = false, defaultValue = "1") @ApiParam(name = "page", value = "page number", required = false, defaultValue = "1") int page,
            @RequestParam(value = "pageSize", required = false, defaultValue = "20") @ApiParam(name = "pageSize", value = "page size", required = false, defaultValue = "20") int pageSize)
            throws Exception {

        Page<Job> pageData = BL.JOB.getJobs(page, pageSize);
        return new Resp(Code.REQUEST_OK, "succ", pageData);
    }

    @ApiOperation("get active jobs")
    @GetMapping("/active")
    public Resp getActiveJobs() throws Exception {

        List<Job> activeJobs = BL.JOB.getActiveJobs();
        return new Resp(Code.REQUEST_OK, "succ", activeJobs);
    }

    @ApiOperation("delete a job & record file")
    @DeleteMapping("/{id}")
    public Resp deleteJob(@PathVariable("id") @ApiParam(name = "id", value = "job id", required = true) String id)
            throws Exception {

        BL.JOB.deleteJob(id);
        return new Resp(Code.REQUEST_OK, "succ, delete data and record file");
    }

    @ApiOperation("get record replay path of job")
    @GetMapping("/http-replay-path/{id}")
    public Resp getHttpReplayPath(
            @PathVariable("id") @ApiParam(name = "id", value = "job id", required = true) String id) throws Exception {
        Job job = BL.JOB.getJob(id);
        if (job == null)
            throw new Exception("job not found");
        return new Resp(Code.REQUEST_OK, "succ", "/record/" + job.getStreamId() + "/"
                + job.getId() + "/index" + Constants.RECORD_PLAYLIST_FILE_SUFFIX);
    }

}
